package org.thrj.wechat.sdk.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.thrj.wechat.sdk.WeChatCommonSdk;
import org.thrj.wechat.sdk.WeChatPushMessageSdk;

import java.util.Map;

@Component
@ConditionalOnBean(WeChatCommonSdk.class)
public class WeChatPushMessageSdkImpl implements WeChatPushMessageSdk {

    @Autowired
    private WeChatCommonSdk weChatCommonSdk;

    @Autowired
    private RestTemplate restTemplate;

    private static final String SubscribeMessageURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";

    @Override
    public void pushMessage(String message_tid, String openId, String page, Map<String, String> param) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("touser", openId);
        requestBody.put("template_id", message_tid);
        // 设置跳转小程序任务页
        requestBody.put("page", page);
        // 构建模板数据
        JSONObject data = new JSONObject();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            // 构造每个字段对应的对象：{ "value": "..." }
            JSONObject fieldObj = new JSONObject();
            fieldObj.put("value", value);
            // 将其放入外层 data 对象中
            data.put(key, fieldObj);
        }
        requestBody.put("data", data);
        // 发送POST请求
        String url = SubscribeMessageURL + "?access_token=" + weChatCommonSdk.getAccessToken();
        restTemplate.postForEntity(url, requestBody, String.class);
    }

}
